const request = require('../../utils/request')
const util = require('../../utils/util');
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    //自定义头部
    navbarHeight: 0,
		classList: [],
		// 分类id
		cate_id: '',
		page: 1,
		isLastPage: false,
		list: [],
    subCategroy:[], // 二级分类
		// subClass:[],//二级分类


		topTablist: [
		],



		// 分类tab列表
		productList: [],
		//控制当前那个按钮点亮
		// curNav: 1,
		//根据此参数来拿第几个分类的数据
		curIndex: 0,

		//选项卡样式
		currentTab: 0,

		//添加购物车
		editSwitch: false,
		location: {},
		clickSecond:false,//是否点击了二级分类
    navWidth:0, // 移动距离
		secondOneId:0, //每个一级分类下二级分类的全部
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function () {
		// if(options.id) {
		// 	this.setData({
		// 		cate_id:options.id,
		// 	})
    // }
    let screenWidth  = wx.getSystemInfoSync().windowWidth / 6
    this.setData({
      navbarHeight: util.getNavbarHeight(),
      navWidth: screenWidth
    })
    this.getList_class()
    var that = this
    getApp().setWatching('cate_id', that.getCateList)
	},
	onShow() {
    let cartList = wx.getStorageSync('cartList')
    if(cartList){
      let list = this.data.list
      list.forEach((item)=>{
        item.cart_num = 0
        item.addSwitch = false
        cartList.forEach((cart)=>{
          if(item.goods_id == cart.goods_id){
            item.cart_num = cart.nums
            item.addSwitch = true
          }
        })
      })
      this.setData({
        list: list
      })
    }
	},
	getCateList(globalCateId) {
    if(globalCateId) {
      let list = this.data.classList
      let index = list.findIndex(el=>el.id == globalCateId)
      let childList = list[index].child || []
      this.setData({
        currentTab:index,
        subCategroy: childList,
        cate_id:childList.length > 0 ? childList[0].id : '', //默认传第一个id
        curIndex:0,
        list: [],
        isLastPage: false,
      })
    }
    if(this.data.cate_id){
      this.getList()
    }
  },
  showClassNav(){
    this.setData({
      showCate: !this.data.showCate, // 更新当前选中
    });
  },
	// 左侧分类
	switchRightTab: function (e) {
		// 获取item项的id，和数组的下标值  
		let id = e.target.dataset.id, index = parseInt(e.target.dataset.index);
		// 把点击到的某一项，设为当前index  
		this.setData({
			curIndex: index,
			cate_id: id,
			list: [],
			isLastPage: false,
			page: 1,
			topTablist:[]
		})
		this.getList()
	},
  subNavTab(e){
    let index = e.detail
    this.changeTabName(index)
  },
	//一级选项卡
	swithNav(e) {
    const index = e.currentTarget.dataset.index;
    this.changeTabName(index)
	},
  changeTabName(index){
    let childList = this.data.classList[index].child;
    console.log('childList==>'+childList)
		this.setData({
			currentTab: index, //更新选中的tab
      clickSecond:true,
      subCategroy: childList || [],
			cate_id: childList.length > 0 ? childList[0].id : '',
			list: [],
			isLastPage: false,
			page: 1
    })
    if(this.data.cate_id){
      this.getList()
    }
  },
	toSearch() {
		wx.navigateTo({
			url: '/pages/home/pages/my/search',
		})
	},
	add(e) {
		let list = this.data.list
		let item = e.currentTarget.dataset.item
		let index = e.currentTarget.dataset.index
		if (!item.addSwitch) {
			item.addSwitch = true
			item.cart_num++
		}
		this.addCartApi(item,index)
		list[index] = item
		this.setData({
			list
		})
	},
	// 购物车加减
	addCartReduce(e) {
		let type = e.currentTarget.dataset.type //1 减 2 加
		let item = e.currentTarget.dataset.item
		let index = e.currentTarget.dataset.index
    let list = this.data.list
    if(type == 2 && item.seckill_rule && item.cart_num == item.seckill_rule.max_nums){
      wx.showToast({
        title:`最多限购${item.seckill_rule.max_nums}件`,
        icon:'none',
        duration:1000
      })
      return
    }
		if (type == 1) {
			if (item.cart_num == 0) {
				// getApp().toast('商品不能再减了~')
				return
			}
			item.cart_num--
		} else {
			item.cart_num++
		}

		this.addCartApi(item, index)
		list[index] = Object.assign(list[index], item)
		this.setData({
			list
		})

	},
	addCartApi(item, index) {
    let list = this.data.list
		request._post('/api?method=cart.add', {
			product_id: item.product_id || item.id,
			nums: item.cart_num,
			num_type: 2,
		}, 'noload').then(res => {
			getApp().getCartNum()
      getApp().globalData.changePoint = true
      if(item.cart_num == 0) {
        list[index].addSwitch =false
        this.setData({
          [`list[${index}]`]: list[index]
        })
			}
		}).catch(res => {
			// 库存不足情况--
			list[index].cart_num--
			if( list[index].cart_num == 0) {
				list[index].addSwitch =false
			}
			this.setData({
				[`list[${index}]`]: list[index]
			})
		})
	},
  /**
	 * 加入购物车弹窗
	 */
	showCartWindow(e) {
    this.setData({
      currentTab: 0
    })
    this.getDetailInfo(e)
 
  },
  	// 获取详情页信息
    getDetailInfo(e) {
      let type = e.currentTarget.dataset.type
      let addcar = e.currentTarget.dataset.addcar
      let index = e.currentTarget.dataset.index
      let item = e.currentTarget.dataset.item
      let _this = this
      request._post('/api?method=goods.goodsinfo', {
        goods_id: item.goods_id
      }).then(res => {
        let list = res.data.products
        list.forEach((obj)=>{
          obj.addSwitch = false
          if (obj.cart_num) {
            obj.addSwitch = true
          }
        })
        _this.setData({
          detailInfo: res.data,
          products: list,
          isPintuan: res.data.is_pin,
          pintuanInfo: res.data.tuan,
          pintuan_list:  res.data.tuan ? res.data.tuan.pin_users :[],
          morenGuige: list ? list[0] :{},
          num: list ? list[0].cart_num > 0 ? list[0].cart_num : 1 : 1,
          guigelist: list,
          isShowCart: true,
          isShowCart_type: type,
          isAddCar: addcar == 1 ? true : false,
          item: item,
          index,
        })
    
      })
    },
    hideCartWindow() {
      this.setData({
        isShowCart: false
      })
    },
  /**
   * 输入框事件
   */
  bindCardManual: function (e) {
    var num = e.detail.value;
    this.setData({
      num: num
    });
  },
  addCardNum(e) {
    let type = e.currentTarget.dataset.type
    let num = this.data.num
    let morenGuige = this.data.morenGuige
    if (type == 1) {
      // 减
      if (num == 1) {
        return getApp().toast('不能再减少了~')
      }
      num--
    } else {
      if (num >= morenGuige.kucun) {
        return getApp().toast('商品库存不足~')
      }
      if(this.data.detailInfo.is_pin && num >= this.data.detailInfo.max_nums){
        return getApp().toast('最多限购'+this.data.detailInfo.max_nums+'件')
      }
      if(this.data.detailInfo.is_seckill && num >= this.data.detailInfo.seckill_rule.max_nums){
        return getApp().toast('最多限购'+this.data.detailInfo.seckill_rule.max_nums+'件')
      }
      num++
    }
    this.setData({
      num
    })
  },
  confirmOrder(){
    this.hideCartWindow()
    let morenGuige = this.data.morenGuige
    morenGuige.cart_num = this.data.num - 1
    this.setData({
      morenGuige: morenGuige
    })
 
    this.addCart({
      item: this.data.morenGuige,
      index: this.data.index
    })
  },
	// 购物车加减
  addCart(e) {
    let item = e.item ? e.item : {}
    let index = e.index ? e.index : 0
		let list = this.data.list
      if (!item.addSwitch) {
          item.addSwitch = true
          item.cart_num++
      }
      this.addCartApi(item, index)
      if(list[index].product_id == item.id){
        list[index].cart_num = item.cart_num
        list[index].addSwitch = item.addSwitch
      }
    
      this.setData({
        list:list
      })
  },
    	/**
	 * 规格
	 */
	switchNav(e) {
		const index = e.currentTarget.dataset.index;
		let item = e.currentTarget.dataset.item
		this.setData({
			currentTab: index, // 更新选中的tab
			morenGuige: item,
			num: 1
		});
	},
	// 获取分类列表
	getList_class() {
		let _this = this
		request._post('/api?method=merchants.goodsClass', {}).then(res => {
      if(res.data.length > 0){
        let list = res.data
        list.forEach(item=>{
          if(item.child.length <= 0){
            item.child = [{
              id: item.id, name: "全部"
            }]
          }
        })
        let child = list[0].child || []
        _this.setData({
          classList: list,
          secondOneId:getApp().globalData.cate_id  ?  getApp().globalData.cate_id  :  '',
          subCategroy: child,
          currentTab:0,
          curIndex: 0,
          cate_id: child.length > 0 ? child[0].id : '',
        })
        let globalCateId = getApp().globalData.cate_id 
        if(globalCateId) {
          let index = list.findIndex(el=>el.id == globalCateId)
          let childList = list[index].child
          _this.setData({
            currentTab:index,
            subCategroy: childList,
            cate_id:childList.length > 0 ? childList[0].id : '', //默认传第一个id
            curIndex:0
          })
        }
        if(_this.data.cate_id){
          _this.getList()
        }
      }
		})
	},
	// 获取商品
	getList() {
		let _this = this
		let isLastPage = this.data.isLastPage
		let location_id = wx.getStorageSync('localXiaoqu') ? wx.getStorageSync('localXiaoqu').id : ''
		request._post('/api?method=merchants.goodsList', {
			key: this.data.key,
			page: this.data.page,
			cate_id: this.data.cate_id,
			// secondary: this.data.currentTab == 1 ? this.data.cate_id : '',
			xiaoqu: location_id
		}).then(res => {
			if (res.data.subclass&&res.data.subclass.length > 0) {
				let subclass = res.data.subclass
				subclass.unshift({
					id: this.data.secondOneId,
					name: '全部'
				})
				_this.setData({
					topTablist: subclass
				})
			} else {
				if(!_this.data.clickSecond) {
					_this.setData({
						topTablist: []
					})
				}
			
			}
			if (res.data && res.data.length == 0) {
				isLastPage = true
			
			} else {
				isLastPage = false
			}

			_this.setData({
				list: _this.data.list.concat(res.data),
			})
			_this.dealList()
		})

	},
	dealList() {
		let list = this.data.list
		list.forEach(function (obj, index) {
			obj.addSwitch = false
			if (obj.cart_num > 0) {
				obj.addSwitch = true
			}
		})
		this.setData({
			list
		})
	},
	toDetail(e) {
		wx.navigateTo({
			url: '/pages/home/pages/my/product-details/product-details?id=' + e.currentTarget.dataset.item.id,
			success: function (res) {
				// success
			},
			fail: function () {
				// fail
			},
			complete: function () {
				// complete
			}
		})
	},
	toSearch() {
		wx.navigateTo({
			url: '/pages/home/pages/my/search/search',
		})
	},
	// 上拉加载
	onReachBottom: function () {
		console.log('哈哈')
		let page = this.data.page
		if (this.data.isLastPage) {
			return
		}
		page++
		this.setData({
			page
		})
		this.getList()
	},
})